<script setup>
import { inject, ref } from "vue";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { inventoryApi, totalApi } from "@/services/cloudlibrary";
import { selectgiftProductStore } from "@/stores/selectgiftProduct";
import { formatPrice } from "@/utils/formatPrice";
import { cate } from "@/services/index";

const selectgiftProductData = selectgiftProductStore();

onShow(() => {
  getList();
  getTotal();
  cateFun();
  numfun();
});

// 库存统计
const total = ref(0);
const getTotal = async () => {
  try {
    // 发送请求
    let res = await totalApi({ cates: cates.value });
    if (res.code === 200) {
      total.value = res.data.total;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

// 我的库存商品
const form = ref({ page: 1, limit: 20 });
const inventoryData = ref([]);
const status = ref("more");
const cates = ref("");
const getList = async () => {
  inventoryData.value = [];
  form.value.page = 1;
  form.value.keyword = keyword.value;
  form.value.cates = cates.value;
  try {
    status.value = "loading";
    // 发送请求
    let res = await inventoryApi(form.value);
    if (res.code === 200) {
      res.data.list.map((item) => {
        item["selectStatus"] = false;
        item["product_num"] = 1;
      });
      let arr = [];
      arr = res.data.list;
      inventoryData.value = inventoryData.value.concat(arr);

      // 判断是否有选择过
      if (selectgiftProductData.selectgiftProduct.length > 0) {
        inventoryData.value.forEach((item1, index1) => {
          selectgiftProductData.selectgiftProduct.forEach((item2, index2) => {
            if (item1.product_id == item2.product_id) {
              item1.product_num = item2.product_num;
              item1.selectStatus = true;
            }
          });
        });
        selectData.value = [];
        inventoryData.value.forEach((item3, index3) => {
          if (item3.selectStatus == true) {
            selectData.value.push(item3);
          }
        });
        selectChecked.value = selectData.value;
        selectCount.value = selectChecked.value.length;
      } else {
        // inventoryData.value = inventoryData.value.concat(arr);
        selectgiftProductData.selectgiftProduct = [];
        selectData.value = [];
        selectChecked.value = [];
        inventoryData.value.forEach((item3, index3) => {
          item3["product_num"] = 1;
          item3["selectStatus"] = false;
        });
      }

      if (res.data.list.length < form.value.limit) {
        status.value = "no-more";
      } else {
        status.value = "more";
      }
      form.value.page++;
    }
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
  }
};

const keyword = ref("");
const aloneChecked = ref(false);
const checkboxValue1 = ref([]);
const selectChecked = ref([]);
const selectData = ref([]);
const giftgoorderData = ref([]);
const selectCount = ref(0);
const show = ref(false);

// 搜索
const searchfun = () => {
  inventoryData.value = [];
  form.value.page = 1;
  form.value.keyword = keyword.value;
  getList();
};

// 加号
const showNumberBox = (index) => {
  let isnew = true;
  if (inventoryData.value[index].quantity > 0) {
    inventoryData.value[index].selectStatus = true;
    if (selectData.value.length <= 0) {
      selectData.value.push(inventoryData.value[index]);
    } else {
      inventoryData.value.forEach((element2, index2) => {
        if (index2 == index) {
          selectData.value.forEach((element, index1) => {
            if (element.product_id == element2.product_id) {
              isnew = false;
              element["selectStatus"] = true;
              element["product_num"] = element.product_num;
              element2.product_num = element.product_num;
            } else {
            }
          });
          if (isnew) {
            inventoryData.value[index2].product_num = 1;
            selectData.value.push(inventoryData.value[index2]);
          }
        }
      });
    }
    // if (inventoryData.value[index].selectStatus) {
    //   selectData.value.push(inventoryData.value[index]);
    // }
    selectgiftProductData.setselectgiftProduct(giftgoorderData.value);
    selectChecked.value = selectData.value;
    selectCount.value = selectChecked.value.length;
  }
};
// 查看明细
const showDeatil = () => {
  show.value = !show.value;
  if (
    selectChecked.value.length === selectCount.value &&
    selectCount.value > 0
  ) {
    aloneChecked.value = true;
  } else {
    aloneChecked.value = false;
  }
};

// 全选
const changeAll = () => {
  aloneChecked.value = !aloneChecked.value;
  selectChecked.value.forEach((item, index) => {
    if (aloneChecked.value) {
      item.selectStatus = true;
      selectCount.value = selectData.value.length;
    } else {
      item.selectStatus = false;
      selectCount.value = 0;
    }
  });
};
// 复选框
const checkboxChange = (e, index) => {
  aloneChecked.value = false;
  selectChecked.value[index].selectStatus =
    !selectChecked.value[index].selectStatus;
  if (selectChecked.value[index].selectStatus) {
    selectCount.value += 1;
  } else {
    selectCount.value -= 1;
  }

  if (selectChecked.value.length === selectCount.value) {
    aloneChecked.value = true;
  } else {
    aloneChecked.value = false;
  }
};

// 选好
const goorderfun = () => {
  selectChecked.value = selectData.value;
  giftgoorderData.value = [];
  selectChecked.value.forEach((item, index) => {
    if (item.product_num > 0) {
      if (!giftgoorderData.value.includes[index] && item.selectStatus) {
        giftgoorderData.value.push(item);
      }
    }
  });
  selectgiftProductData.setselectgiftProduct(giftgoorderData.value);
  if (giftgoorderData.value.length > 0) {
    uni.navigateTo({
      url: "/pages/cloudlibrary/productGift/index",
    });
  } else {
    uni.showToast({
      title: "请选择商品",
      icon: "none",
    });
  }
};
// 步进器，数量
const valChange1 = (e, index) => {
  inventoryData.value.forEach((item1, index1) => {
    if (index1 == index) {
      selectData.value.forEach((item2, index2) => {
        if (item1.selectStatus == true) {
          if (item1.product_id == item2.product_id) {
            item1.product_num = e.value;
            item2.product_num = e.value;
          }
        }
      });
    }
  });
  // inventoryData.value[index].product_num = e.value;
};
// 步进器，数量
const valChange2 = (e, index) => {
  selectData.value.forEach((item4, index4) => {
    if (index4 == index) {
      inventoryData.value.forEach((item3, index3) => {
        if (item3.selectStatus == true) {
          if (item3.product_id == item4.product_id) {
            item3.product_num = e.value;
            item4.product_num = e.value;
          }
        }
      });
    }
  });
  // inventoryData.value[index].product_num = e.value;
};

const close = () => {
  show.value = false;
};

//计算商品总数
function numfun() {
  let num = 0;
  if (selectData.value.length > 0) {
    selectData.value.forEach((element, index) => {
      if (element.selectStatus) {
        num += element.product_num;
      }
    });
    return num;
  } else {
    return num;
  }
}

// 分类查询
const cateData = ref([]);
const cateFun = async () => {
  try {
    // 发送请求
    let res = await cate();
    cateData.value = res.data;
  } catch (e) {
    uni.showToast({
      title: e.info,
      icon: "none",
    });
    cateData.value = "";
  }
};

const showPopup = ref(false);
const type_classIndex = ref("");
const closepopup = () => {
  showPopup.value = false;
  cates.value = "";
  type_classIndex.value = "";
  inventoryData.value = [];
  form.value.page = 1;
  form.value.keyword = keyword.value;
  getTotal();
  getList();
};
// 筛选确认
const popupSubmit = () => {
  showPopup.value = false;
  inventoryData.value = [];
  form.value.page = 1;
  form.value.keyword = keyword.value;
  getTotal();
  getList();
};
const closecate = () => {
  showPopup.value = false;
  // cates.value=""
  // type_classIndex.value=""
  // inventoryData.value = [];
  // form.value.page = 1;
  // form.value.keyword = keyword.value;
  // getTotal();
  // getList();
};
const selectClassType = (index) => {
  inventoryData.value = [];
  form.value.page = 1;
  type_classIndex.value = index;
  cates.value = index;
  getTotal();
  getList();
};

// 刷新
const refresh = () => {
  inventoryData.value = [];
  form.value.page = 1;
  form.value.keyword = keyword.value;
  getTotal();
  getList();
};
</script>

<template>
  <view class="content">
    <view class="content-top">
      <up-search
        placeholder="搜索商品"
        v-model="keyword"
        @search="searchfun"
        :showAction="false"
      ></up-search>
      <view class="search" @click="showPopup = true">
        <image
          src="@/pages/cloudlibrary/static/search.png"
          mode="scaleToFill"
        />
      </view>
    </view>
    <view class="content-num"
      ><view
        >当前库存余:<text>{{ total }}</text></view
      >
    </view>
    <view
      class="content-list"
      v-show="inventoryData && inventoryData.length > 0"
    >
      <view
        class="content-list-item"
        v-for="(item, index) in inventoryData"
        :key="index"
      >
        <view class="content-list-item-left">
          <image :src="item.product.image" mode="aspectFill" />
          <view class="content-list-item-dec">
            <view class="content-list-item-name">{{
              item.product.store_name
            }}</view>
            <view class="goods-dec">默认</view>

            <view class="content-list-item-price"
              >￥{{ formatPrice(item.product.price) }}</view
            >
          </view>
        </view>
        <view class="content-list-item-right"> 余{{ item.quantity }} </view>

        <view class="select-shop">
          <up-number-box
            :min="0"
            :max="item.quantity"
            v-model="item.product_num"
            :show="item.selectStatus"
            v-if="item.selectStatus"
            @change="
              (e) => {
                valChange1(e, index);
              }
            "
            bgColor="#ffffff"
          ></up-number-box>
          <view class="select-shop-add" v-if="!item.selectStatus">
            <up-icon
              name="plus"
              color="#262626"
              size="30rpx"
              @click="showNumberBox(index)"
            ></up-icon>
          </view>
        </view>
      </view>
    </view>
    <view class="nodate-bt" v-if="inventoryData.length === 0">
      <image src="/static/nodate/nodate.png" mode="widthFix"></image>
    </view>

    <uni-load-more color="#c6c5c3" :status="status" />
  </view>

  <view class="foodr-bt">
    <view class="foodr-bt-left">
      <up-checkbox
        :customStyle="{ marginBottom: '8px' }"
        label="全选"
        name="agree"
        usedAlone
        shape="circle"
        size="48rpx"
        activeColor="#F3498B "
        v-model:checked="aloneChecked"
        @change="changeAll"
        v-if="show"
      >
      </up-checkbox>
    </view>
    <view class="foodr-bt-right">
      <view class="bt-text"
        >已选{{ numfun() }}<text @click="showDeatil">查看明细</text
        ><up-icon
          :name="true ? 'arrow-up' : 'arrow-down'"
          color="#F3498B "
          size="38rpx"
        ></up-icon
      ></view>
      <view class="bt-sbuit" @click="goorderfun()">选好了</view></view
    >
  </view>

  <up-popup
    :show="show"
    mode="bottom"
    @close="close"
    @open="open"
    :closeable="true"
    round="20"
  >
    <view class="content-list-title">已选商品</view>
    <view class="content-list content-list-view">
      <scroll-view
        :scroll-top="scrollTop"
        scroll-y="true"
        class="scroll-Y"
        :show-scrollbar="false"
        @scrolltoupper="upper"
        @scrolltolower="lower"
        @scroll="scroll"
      >
        <up-checkbox-group v-model="checkboxValue1" placement="column">
          <view
            class="content-select-item"
            v-for="(item, index) in selectData"
            :key="index"
          >
            <up-checkbox
              :customStyle="{ marginBottom: '8px' }"
              shape="circle"
              activeColor="#F3498B "
              size="48rpx"
              @change="
                (e) => {
                  checkboxChange(e, index);
                }
              "
              :name="item.product_id"
              :key="item.product_id"
              :checked="item.selectStatus"
            >
            </up-checkbox>
            <view class="content-list-item select-content-list-item">
              <view class="content-list-item-left">
                <image :src="item.product.image" mode="aspectFill" />
                <view class="content-list-item-dec">
                  <view class="content-list-item-name">{{
                    item.product.store_name
                  }}</view>
                  <view class="goods-dec">默认</view>

                  <view class="content-list-item-price"
                    >￥{{ item.product.price }}</view
                  >
                </view>
              </view>

              <view class="content-list-item-right">
                余{{ item.quantity }}
              </view>

              <view class="select-shop select-shop-k">
                <up-number-box
                  bgColor="#ffffff"
                  v-model="item.product_num"
                  :min="0"
                  :max="item.quantity"
                  @change="
                    (e) => {
                      valChange2(e, index);
                    }
                  "
                ></up-number-box>
                <!-- <view class="select-shop-add">
                  <up-icon name="plus" color="#262626" size="30rpx"></up-icon>
                </view> -->
              </view>
            </view>
          </view>
        </up-checkbox-group>
      </scroll-view>
    </view>
  </up-popup>

  <!-- 筛选 -->
  <u-popup
    :show="showPopup"
    mode="bottom"
    round="10"
    @close="closecate"
    @open="open"
    closeable
    class="showPopup"
  >
    <view class="popup-content">
      <view class="popup-content-title">筛选</view>
      <u-line></u-line>
      <view class="popup-content-dec">
        <view class="popup-content-card">
          <text>分类</text>
          <view class="popup-content-card-btn">
            <view v-for="(item, index) in cateData" :key="index">
              <u-button
                class="popup-button"
                @click="selectClassType(item.id)"
                :class="
                  type_classIndex === item.id ? 'popup-button-active' : ''
                "
              >
                {{ item.name }}
              </u-button>
            </view>
          </view>
        </view>
      </view>

      <view class="popup-content-box">
        <view class="popup-content-bt">
          <u-button
            class="popup-content-qx"
            text="取消"
            @click="closepopup"
          ></u-button>
          <u-button
            class="popup-content-cl"
            text="筛选"
            @click="popupSubmit"
          ></u-button>
        </view>
      </view>
    </view>
  </u-popup>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
